package com.sanda.androidcourse.chapter11;

import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.sanda.androidcourse.R;

public class WebJsActivity extends AppCompatActivity {

    private WebView webView;
    private Button btnExecuteJs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_web_js);

        webView = findViewById(R.id.webview);
        btnExecuteJs = findViewById(R.id.btnExecuteJs);

        // 启用 JS
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        // 必须设置 WebChromeClient 才能弹出 JS 弹窗
        webView.setWebChromeClient(new WebChromeClient());

        // 加载一个简单 HTML 页面
        String htmlData = "<html><body><h2>WebView 页面</h2></body></html>";
        webView.loadDataWithBaseURL(null, htmlData, "text/html", "UTF-8", null);

        // 点击按钮执行 JS 代码
        btnExecuteJs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                webView.evaluateJavascript("javascript:alert('你好，这是JS弹窗！')", null);
            }
        });
    }
}